# -*- coding: utf-8 -*-
from shlex import split
from subprocess import Popen, PIPE,run
from re import sub

# import chardet

file_path_multi = "./WR-IMP-MIB-multi.txt"
file_path_node = "./WR-IMP-MIB-node.txt"
file_path_wrpc = "./WR-WRPC-MIB.txt"
file_path_mas = "./WR-IMP-MIB-mas.txt"
# chardet.detect(msg)["encoding"]

def ping(host):
    result = run(["ping","-c","1","-W","1",host],capture_output=True,encoding="utf8")
    if result.returncode == 0:
        return True
    else:
        print(host + "连接失败，请检查")
        return False

def snmpset(community: str = "public",file_path:str = None, host: str = None, OIDname: str = None, mask: str = None, set_type: str = None, set_value: float = None):
    command = "snmpset -v 2c -c {} -m {} {} {} {} {}".format(
        community, file_path, host, OIDname, set_type, set_value)
    # print(command)
    try:
        proc = Popen(split(
            command), shell=False, stdout=PIPE, stderr=PIPE)
        proc.wait(timeout=0.1)
        if proc.poll() == 0:
            msg = proc.stdout.read().decode("gb2312")
            msg = msg.split("{}".format(mask))
            msg = sub("[^\d]".format(mask), "", msg[1])
        else:
            msg = proc.stderr.read().decode("gb2312")
    except:
        msg = "\""+command + "\" is Error"
    return msg


def snmpget(community: str = "public", file_path:str = None,host: str = None, OIDname: str = "impWavePatternTable1"):
    # command = "echo {} {} {}".format(
    #     community, mask, set_value)
    # proc = Popen(split(
    #     command), shell=True, stdout=PIPE, stderr=PIPE)
    command = "snmpwalk -v 2c -c {} -m {} {} {}".format(
        community, file_path, host, OIDname)
    try:
        proc = Popen(split(
            command), shell=False, stdout=PIPE, stderr=PIPE)
        proc.wait(timeout=1)
        if proc.poll() == 0:
            msg = proc.stdout.read().decode("gb2312")
            # msg = msg.split("{}".format(mask))
            # msg = sub("[^\d]".format(mask), "", msg)
        else:
            msg = proc.stderr.read().decode("gb2312")
    except:
        msg = "\""+command + "\" is Error"
    # print(msg)
    return msg



if __name__ == "__main__":
    # # 测试
    # a = snmpget(file_path=file_path_mas,host="10.10.14.28",OIDname="impOvertime")
    # print(a)
    # a = snmpset(file_path=file_path_mas,host="10.10.14.28",OIDname="impCtrlApply.0",set_type="i",set_value=31,mask="INTEGER:")
    # print(a)
    # a = snmpget(file_path=file_path_mas,host="10.10.14.28",OIDname="impOvertime")
    # print(a)
    # # print(a)
    import time
    start = time.time()
    print(ping("10.10.14.36"))
    print(time.time() - start)
    
    
    